package com.demo.oauth2jFinalShiroClient.oAuth2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class OAuth2Realm extends AuthorizingRealm {

	@Override
	public Class<?> getAuthenticationTokenClass() {
		return ThirdPartToken.class;
	}

	@Override
	public String getName() {
		return OAuth2Realm.class.getSimpleName();
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Collection<?> fromRealm = principals.fromRealm(getName());
		if (!fromRealm.isEmpty()) {
			List<Object> list = new ArrayList<>(fromRealm);
			Object principal = list.get(0);
			if (TokenHolder.USER_OAUTH_TOKEN_MAP.containsKey(principal)) {
				ThirdPartToken thirdPartToken = (ThirdPartToken)TokenHolder.USER_OAUTH_TOKEN_MAP.get(principal);
				SimpleAccount simpleAccount = new SimpleAccount(principal, thirdPartToken.getAccessToken(), getName());
				simpleAccount.addRole(thirdPartToken.getChannel());
				simpleAccount.addRole("thirdPart");
				return simpleAccount;
			}			
		}
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        Object principal = token.getPrincipal();
		if (TokenHolder.USER_OAUTH_TOKEN_MAP.containsKey(principal)) {
			SimpleAccount simpleAccount = new SimpleAccount(principal, TokenHolder.USER_OAUTH_TOKEN_MAP.get(principal).getCredentials(), getName());
			return simpleAccount;
		}	
        return null;
	}

}
